package cn.fch.gotrip.exception;

import cn.fch.gotrip.api.BeanResponse;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: Day60
 * @description:
 * @CreatedBy: fch
 * @create: 2023-01-11 16:28
 **/
@Component
public class MyException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex instanceof ValueException){
            writerResponse(response, BeanResponse.badRequest(ex.getMessage()));
        }
        else if (ex instanceof NotFoundException){
            writerResponse(response, BeanResponse.notFound(ex.getMessage()));
        }
        return null;
    }

    private void writerResponse(HttpServletResponse response ,BeanResponse beanResponse){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        try {
            writer = response.getWriter();
            writer.write(JSONObject.toJSONString(beanResponse));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }
}
